#include "compile_run.hpp"
#include "../Comm/httplib.h"

using namespace httplib;

static const string LogFile = "/var/log/OJ_compiler.log";

int main(int argc, char* argv[])
{
    
    //测试
    /*
    string str = ns_util::FileUiil::ReadFile("./temp/test.cpp");
    ns_protocol::Request rt;
    rt.Set(str, 1, 1024 * 10);
    str = rt.Serialization();
    cout << str;

    string ret = ns_complie_run::CompileAndRun::Start(str);
    cout << ret;
    */

    if (argc != 2)
    {
        cout << "Usage:\n\t./Compile_server Port" << endl; 
        return -1;
    }

    //设置守护进程
    daemon(1, 1);
    //对日志(标准输出)做重定向
    int fd = open(LogFile.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
    if (fd == -1)
    {
        cout << "创建/写入日志文件权限不足:" << LogFile << endl;
        exit(-1);
    }
    dup2(fd, 1);

    //使用第三方开源网络库搭建网络通信
    Server svr;
    
    //注册服务
    svr.Post("/compile_and_run", [](const Request& ret, Response& rse){
        rse.set_content(ns_complie_run::CompileAndRun::Start(ret.body), "application/json");
    });

    //启动
    svr.listen("0.0.0.0", atoi(argv[1]));

    return 0;
}